package com.huanglejing.shanggou.activity

import android.content.Intent
import android.os.Bundle
import android.support.v4.util.ArrayMap
import com.google.gson.JsonObject
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.bean.AddressListBean
import com.huanglejing.shanggou.bean.CreateOrderBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.*
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheGoodsBeanDao
import com.huanglejing.shanggou.greendao.CacheOrderBean
import com.huanglejing.shanggou.greendao.CacheOrderBeanDao
import com.huanglejing.shanggou.interfaces.SaveOrderContract.SaveOrderPresenter
import com.huanglejing.shanggou.interfaces.SaveOrderContract.SaveOrderView
import com.huanglejing.shanggou.presenterimpl.SaveOrderImpl
import com.huanglejing.shanggou.utils.ToastUtils
import com.huanglejing.shanggou.utils.checkEmpty
import com.huanglejing.shanggou.utils.formatNum
import kotlinx.android.synthetic.main.activity_save_order.*
import rx.Observable

class SaveOrderActivity : AppBaseActivity<SaveOrderPresenter<SaveOrderView>, SaveOrderView>(), SaveOrderView {
    //   private var mData: ArrayList<AddressListBean> = arrayListOf()
    private var orderBean: CacheOrderBean? = null
    private var companyId: String? = ""
    private var allMoney: Double = 0.00
    var list: List<CacheGoodsBean>? = null
    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
        }
        return Observable.just(map)
    }

    override fun getOrderParams(): Observable<Map<String, Any>> {
        var goodsData = arrayListOf<CreateOrderBean>()
        list?.forEachIndexed { index, cacheOrderBean ->
            val bean = CreateOrderBean()
            bean.categoryGUID = cacheOrderBean.categoryGUID
            bean.goodNO = cacheOrderBean.no
            bean.num = cacheOrderBean.num
            bean.price = cacheOrderBean.price
            bean.totalPrice = cacheOrderBean.totalPrice
            goodsData?.add(bean)
        }
        val map = ArrayMap<String, Any>().apply {
            put("companyId", orderBean?.companyId ?: "")
            put("customerId", orderBean?.customerId ?: "")
            put("bz", orderBean?.bz ?: "")
            put("goods", goodsData)
        }
        return Observable.just(map)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        companyId = intent?.extras?.getString("companyId")
        var allOrder = getCacheOrders()
        allOrder?.forEachIndexed { index, cacheOrderBean ->
            if (companyId.equals(cacheOrderBean.companyId)) {
                orderBean = cacheOrderBean
            }

        }
        var goods = orderBean?.goods?.split("#")?.toList()
        list = getCacheGoods()?.filter { goods?.contains(it?.id?.toString() ?: "") ?: false }
        list?.forEachIndexed { index, cacheOrderBean ->
            allMoney = allMoney.plus(cacheOrderBean?.totalPrice?.toDoubleOrNull() ?: 0.00)
        }

        initWidget()
    }

    private fun initWidget() {
        setAPPTitle(resources.getString(R.string.str_save_order))
        tv_save_order_price?.text = "${formatNum(allMoney)}€"
        tv_save_order_total?.text = "${formatNum(allMoney)}€"
        et_rubish?.setText(orderBean?.bz ?: "")
        ll_address_container?.setOnClickListener {
            val intent = Intent(this@SaveOrderActivity, MineShippingAddressActivity::class.java)
            val bun = Bundle()
            bun.putBoolean("isGetAddress", true)
            intent?.putExtras(bun)
            startActivityForResult(intent, 100)
        }

        if (!orderBean?.companyName.checkEmpty() && !orderBean?.companyAddress.checkEmpty()
                && !orderBean?.linkTelephone.checkEmpty()) {
            tv_save_order_name?.text = orderBean?.companyName ?: ""
            tv_save_order_address?.text = orderBean?.companyAddress ?: ""
            tv_save_order_code?.text = "${orderBean?.postalCode}"
            tv_save_order_city?.text = "${orderBean?.city}"
            tv_save_order_province?.text = "${orderBean?.province}"
            tv_save_order_phone?.text = orderBean?.linkTelephone ?: ""
        }
        tv_save_order_save?.setOnClickListener {
            mBasePresenter?.saveOrder()
        }
    }

    override fun <T> showContent(data: T?) {

        try {
            val newData = data as? ArrayList<AddressListBean>
            if (newData != null && orderBean?.companyName.checkEmpty() && orderBean?.companyAddress.checkEmpty()
                    && orderBean?.linkTelephone.checkEmpty()) {
                tv_save_order_name?.text = newData?.getOrNull(0)?.companyName ?: ""
                tv_save_order_address?.text = newData?.getOrNull(0)?.companyAddress ?: ""
                tv_save_order_code?.text = "${newData?.getOrNull(0)?.postalCode}"
                tv_save_order_city?.text = "${newData?.getOrNull(0)?.city} "
                tv_save_order_province?.text = "${newData?.getOrNull(0)?.province}"
                tv_save_order_phone?.text = newData?.getOrNull(0)?.linkTelephone ?: ""
            }
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    override fun showSaveResult(data: JsonObject) {
        if (data?.get("data")?.isJsonObject == true
                && data?.get("status")?.asString?.equals("00") ?: false) {
            ToastUtils.toastLong(resources.getString(R.string.str_add_order_success))
//            orderBean?.companyName=tv_save_order_name?.text?.toString()
//            orderBean?.companyAddress=tv_save_order_address?.text?.toString()
//            orderBean?.postalCode=tv_save_order_code?.text?.toString()
//            orderBean?.city=tv_save_order_city?.text?.toString()
//            orderBean?.province=tv_save_order_province?.text?.toString()
//            orderBean?.linkTelephone=tv_save_order_phone?.text?.toString()
//            orderBean?.bz=et_rubish?.text?.toString()
            list?.forEach {
                beanDao?.delete(it)
            }
            orderDao?.delete(orderBean)
            finish()
        } /*else if (
                data?.get("data")?.asString?.equals("1") ?: false
                && data?.get("status")?.asString?.equals("00") ?: false) {
            ToastUtils.toastLong("添加收获地址成功")
            finish()
        }*/
    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
    }

    override fun createPresenter(): SaveOrderPresenter<SaveOrderView> = SaveOrderImpl()

    override fun getLayoutId(): Int = R.layout.activity_save_order

    override fun requestPermission() {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 200 && data != null) {
            var bean = data?.getSerializableExtra("AddressListBean") as? AddressListBean
            tv_save_order_name?.text = bean?.companyName ?: ""
            tv_save_order_address?.text = bean?.companyAddress ?: ""
            tv_save_order_code?.text = "${bean?.postalCode}"
            tv_save_order_city?.text = "${bean?.city} "
            tv_save_order_province?.text = "${bean?.province}"

            tv_save_order_phone?.text = bean?.linkTelephone ?: ""
        }
    }

    override fun finish() {
        orderBean?.companyName = tv_save_order_name?.text?.toString()
        orderBean?.companyAddress = tv_save_order_address?.text?.toString()
        orderBean?.postalCode = tv_save_order_code?.text?.toString()
        orderBean?.city = tv_save_order_city?.text?.toString()
        orderBean?.province = tv_save_order_province?.text?.toString()
        orderBean?.linkTelephone = tv_save_order_phone?.text?.toString()
        orderBean?.bz = et_rubish?.text?.toString()
        orderDao?.update(orderBean)
        super.finish()
    }
}
